package com.iflytek.read;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.iflytek.read.bean.FloatWindowBean;
import com.iflytek.read.util.DownloaderUtil;
import com.iflytek.read.util.LogUtil;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wangshuai
 */
public class MusicPlayerService extends Service implements DownloaderUtil.DownloadListener {

    private static final String TAG = "MusicPlayerService";

    private int currentType = -1;

    public void setCurrentType(int currentType) {
        this.currentType = currentType;
        if (null != mFloatBean) {
            mFloatBean.setType(currentType);
        }
    }

    private static final String CHANNEL_ID = "MusicPlayerChannel";
    private static final int NOTIFICATION_ID = 1;

    public Messenger activityMessenger;

    private AudioManager audioManager;
    /**
     * 用于保存mediaPlayer2的固定音量
     */
    private int fixedVolumeLevel;
    private FloatWindowBean mFloatBean;

    public FloatWindowBean getFloatBean() {
        return mFloatBean;
    }

    /**
     * mediaPlayer1 主要用于播放主要音频内容（如朗读内容），默认处理 WAV 文件
     * mediaPlayer2 主要用于播放背景音乐，默认处理 MP3 文件
     */
    private MediaPlayer mediaPlayer1;
    private MediaPlayer mediaPlayer2;
    private String url1;
    private String url2;

    public String getUrl2() {
        return url2;
    }

    private boolean isPrepared1 = false;
    private boolean isPrepared2 = false;

    private final IBinder binder = new MusicPlayerBinder(this);

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //createNotificationChannel();
        //startForeground(NOTIFICATION_ID, createNotification());

        mediaPlayer1 = new MediaPlayer();
        mediaPlayer2 = new MediaPlayer();

        // 初始化AudioManager
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        // 初始化时获取当前音量作为mediaPlayer2的固定音量
        this.fixedVolumeLevel = 20;
        Log.i(TAG, "fixedVolumeLevel  ==  " + fixedVolumeLevel);

        setupMediaPlayer(mediaPlayer1, Constant.PLAYER_ID_1);
        setupMediaPlayer(mediaPlayer2, Constant.PLAYER_ID_2);

        // 设置mediaPlayer2使用独立的音频会话ID
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                // 设置音频用途（媒体播放）
                .setUsage(AudioAttributes.USAGE_MEDIA)
                // 设置音频内容类型（音乐）
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build();
        mediaPlayer2.setAudioAttributes(audioAttributes);
        int audioSessionId = mediaPlayer2.getAudioSessionId();
        mediaPlayer2.setAudioSessionId(audioSessionId);

        // 注册音量监听
        registerVolumeReceiver();
    }

    private void registerVolumeReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_VOLUME_CHANGED);
        registerReceiver(volumeReceiver, filter);
    }

    private final BroadcastReceiver volumeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constant.ACTION_VOLUME_CHANGED.equals(intent.getAction())) {
                updateVolumes();
            }
        }
    };

    private void updateVolumes() {
        // 获取当前系统音量
        int currentSystemVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

        // 更新mediaPlayer1的音量
        float volume1 = calculateVolume(currentSystemVolume);
        if (mediaPlayer1 != null && isPrepared1) {
            mediaPlayer1.setVolume(volume1, volume1);
        }

        // mediaPlayer2保持固定音量
        float fixedVolume = calculateVolume(fixedVolumeLevel);
        if (mediaPlayer2 != null && isPrepared2) {
            mediaPlayer2.setVolume(fixedVolume, fixedVolume);
        }
    }

    private float calculateVolume(int volumeLevel) {
        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        return (float) volumeLevel / (float) maxVolume;
    }

    /**
     * 当需要改变mediaPlayer2的固定音量时调用
     * @param level 等级
     */
    public void setFixedVolumeLevel(int level) {
        this.fixedVolumeLevel = level;
        updateVolumes();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    private void setupMediaPlayer(MediaPlayer player, int playerId) {
        player.setOnCompletionListener(mp -> {
            if (completionCallback != null && Constant.PLAYER_ID_1 == playerId && mFloatBean != null) {
                //Log.i(TAG, "mFloatBean  ==  " + mFloatBean);
                completionCallback.getNextAudioUrl(playerId, mFloatBean, new ReadWebViewActivity.NextAudioCallback() {
                    @Override
                    public void onNextAudioReady(FloatWindowBean bean) {
                        if (bean != null && bean.getFilePath() != null) {
                            //Log.i(TAG, "Playing next audio: " + bean);
                            String fileName = bean.getChapterId() + "_" + System.currentTimeMillis() + ".wav";
                            // 开始下载
                            DownloaderUtil.downloadWavFile(getApplicationContext(), bean, bean.getUrl1(), fileName, MusicPlayerService.this);
                            // 更新当前播放的bean
                            mFloatBean = bean;
                        } else {
                            Log.i(TAG, "No more audio to play");
                            mp.stop();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        LogUtil.e(TAG, "Error getting next audio: " + e.getMessage());
                        mp.stop();
                    }
                });
            }
        });

        player.setOnErrorListener((mp, what, extra) -> {
            LogUtil.e(TAG, "MediaPlayer " + playerId + " error: what=" + what + ", extra=" + extra);
            return false;
        });
    }

    public void playAudio(FloatWindowBean bean, int playerId) {
        this.mFloatBean = bean;
        if (Constant.PLAYER_ID_1 == playerId) {
            url1 = bean.getFilePath();
            playAudioForPlayer(bean.getFilePath(), mediaPlayer1, playerId);
        } else {
            url2 = bean.getUrl2();
            playAssetsMp3(url2);
        }
    }

    private void playAudioForPlayer(String filePath, MediaPlayer player, int playerId) {
        try {
            if (player.isPlaying()) {
                player.stop();
            }
            player.reset();
            player.setDataSource(filePath);
            player.prepareAsync();

            // 动态设置播放速度
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (mFloatBean != null && mFloatBean.getSpeed() != null) {
                    float speed = getPlaybackSpeed(mFloatBean.getSpeed());
                    player.setPlaybackParams(player.getPlaybackParams().setSpeed(speed));
                    Log.i(TAG, "Setting playback speed to: " + speed);
                }
            } else {
                // 旧设备不提供变速功能
                Log.i(TAG, "Playback speed not supported on this device");
            }

            // 设置准备监听器以处理seekPosition
            player.setOnPreparedListener(mp -> {
                // 1. 更新准备状态
                if (Constant.PLAYER_ID_1 == playerId) {
                    isPrepared1 = true;
                } else {
                    isPrepared2 = true;
                }

                // 2. 检查并处理 seekPosition（假设存储的是秒）
                if (mFloatBean != null && !TextUtils.isEmpty(mFloatBean.getSeekPosition())) {
                    try {
                        int seekPositionSec = Integer.parseInt(mFloatBean.getSeekPosition());
                        int seekPositionMs = seekPositionSec * 1000;
                        if (seekPositionMs > 0 && seekPositionMs < mp.getDuration()) {
                            Log.i(TAG, "Seeking to: " + seekPositionMs + "ms");
                            mp.seekTo(seekPositionMs);
                            mFloatBean.setSeekPosition("0");
                        }
                    } catch (NumberFormatException e) {
                        LogUtil.e(TAG, "Invalid seekPosition: " + mFloatBean.getSeekPosition());
                    }
                }

                mp.start();
                updateVolumes(); // 确保播放时音量设置正确
            });

            if (Constant.PLAYER_ID_1 == playerId) {
                isPrepared1 = false;
            } else {
                isPrepared2 = false;
            }
        } catch (IOException e) {
            LogUtil.e(TAG, "Error setting data source for player " + playerId, e);
        }
    }

    public void pauseAudio(int playerId) {
        if (Constant.PLAYER_ID_1 == playerId && mediaPlayer1.isPlaying()) {
            mediaPlayer1.pause();
        } else if (Constant.PLAYER_ID_2 == playerId && mediaPlayer2.isPlaying()) {
            mediaPlayer2.pause();
        }
    }

    public void resumeAudio(int playerId) {
        if (Constant.PLAYER_ID_1 == playerId && isPrepared1 && !mediaPlayer1.isPlaying()) {
            mediaPlayer1.start();
        } else if (Constant.PLAYER_ID_2 == playerId && isPrepared2 && !mediaPlayer2.isPlaying()) {
            mediaPlayer2.start();
        }
    }

    public void stopAudio(int playerId) {
        if (Constant.PLAYER_ID_1 == playerId) {
            if (mediaPlayer1.isPlaying()) {
                mediaPlayer1.stop();
            }
            mediaPlayer1.reset();
            isPrepared1 = false;
        } else {
            if (mediaPlayer2.isPlaying()) {
                mediaPlayer2.stop();
            }
            mediaPlayer2.reset();
            isPrepared2 = false;
            this.url2 = null;
        }
    }

    public boolean isPlaying(int playerId) {
        if (Constant.PLAYER_ID_1 == playerId) {
            return mediaPlayer1.isPlaying();
        } else {
            return mediaPlayer2.isPlaying();
        }
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "Music Player Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(serviceChannel);
            }
        }
    }

    private Notification createNotification() {
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("有声朗读")
                .setContentText("Playing audio in background")
                .setSmallIcon(android.R.drawable.ic_media_play)
                .build();
    }

    public MediaPlayer getMediaPlayer1() {
        if (null != mediaPlayer1) {
            return mediaPlayer1;
        }

        return null;
    }

    private ReadWebViewActivity.OnCompletionCallback completionCallback;

    public void setOnCompletionCallback(ReadWebViewActivity.OnCompletionCallback callback) {
        this.completionCallback = callback;
    }

    public MediaPlayer getMediaPlayer2() {
        if (null != mediaPlayer2) {
            return mediaPlayer2;
        }

        return null;
    }

    public void startPlayer() {
        if (null != mediaPlayer1 && !TextUtils.isEmpty(url1)) {
            mediaPlayer1.start();
        }
        if (null != mediaPlayer2 && !TextUtils.isEmpty(url2)) {
            playAssetsMp3(url2);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        // 取消注册广播接收器
        unregisterReceiver(volumeReceiver);

        if (mediaPlayer1 != null) {
            mediaPlayer1.release();
        }
        if (mediaPlayer2 != null) {
            mediaPlayer2.release();
        }
    }

    @Override
    public void onDownloadSuccess(FloatWindowBean bean, File file) {
        Log.i(TAG, "service--onDownloadSuccess  ==  " + currentType);
        if (Constant.TYPE_CURRENT_PLAY != currentType) {
            if (file.exists()) {
                bean.setFilePath(file.getAbsolutePath());
                Log.i(TAG, "bean222  ==  " + bean);
                playAudio(bean, Constant.PLAYER_ID_1);

                // 使用 Messenger 发送消息
                if (activityMessenger != null) {
                    try {
                        Message msg = Message.obtain();
                        msg.what = Constant.SERVICE_SEND_MSG_TYPE;
                        msg.obj = bean.getNovelId();
                        activityMessenger.send(msg);
                    } catch (RemoteException e) {
                        LogUtil.e(TAG, "Failed to send message to activity", e);
                    }
                }
            }
        }

        currentType = -1;
    }

    @Override
    public void onDownloadFailed(Exception e) {}

    @Override
    public void onProgressUpdate(int progress) {
        Log.i(TAG, "progress  ==  " + progress);
    }

    @Override
    public void onDownloadCancelled() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                // 更新UI，显示下载已取消
                Toast.makeText(getApplicationContext(), "下载已取消", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private float getPlaybackSpeed(String speed) {
        switch (speed) {
            case "25":
                return 0.5f;
            case "70":
                return 2.0f;
            case "75":
                return 3.0f;
            case "100":
                return 4.0f;
            default:
                return 1.0f;
        }
    }

    /**
     * 获取当前播放音频的总时长（秒）
     * @param playerId 播放器ID（1或2）
     * @return 总时长（秒），如果播放器未准备返回-1
     */
    public int getTotalDuration(int playerId) {
        if (Constant.PLAYER_ID_1 == playerId) {
            if (mediaPlayer1 != null && isPrepared1) {
                // 毫秒转秒
                return mediaPlayer1.getDuration() / 1000;
            }
        } else if (Constant.PLAYER_ID_2 == playerId) {
            if (mediaPlayer2 != null && isPrepared2) {
                // 毫秒转秒
                return mediaPlayer2.getDuration() / 1000;
            }
        }
        return -1;
    }

    /**
     * 获取当前音频已经播放的时长（秒）
     * @param playerId 播放器ID（1或2）
     * @return 已播放时长（秒），如果播放器未准备返回-1
     */
    public int getCurrentPosition(int playerId) {
        if (Constant.PLAYER_ID_1 == playerId) {
            if (mediaPlayer1 != null && isPrepared1) {
                // 毫秒转秒
                return mediaPlayer1.getCurrentPosition() / 1000;
            }
        } else if (Constant.PLAYER_ID_2 == playerId) {
            if (mediaPlayer2 != null && isPrepared2) {
                // 毫秒转秒
                return mediaPlayer2.getCurrentPosition() / 1000;
            }
        }
        return -1;
    }

    /**
     * 获取当前音频剩余未播放的时长（秒）
     * @param playerId 播放器ID（1或2）
     * @return 剩余时长（秒），如果播放器未准备返回-1
     */
    public int getRemainingTime(int playerId) {
        int total = getTotalDuration(playerId);
        if (total == -1) {
            return -1;
        }
        int current = getCurrentPosition(playerId);
        if (current == -1) {
            return -1;
        }
        return total - current;
    }

    /**
     * 获取 raw 文件夹中的 MP3 文件列表
     * @return MP3 文件名和资源ID的映射
     */
    public Map<String, Integer> getRawMp3Files() {
        Map<String, Integer> mp3Files = new LinkedHashMap<>();

        // 获取所有 raw 资源
        Field[] fields = R.raw.class.getFields();
        for (Field field : fields) {
            try {
                // 不带后缀的名称（如 "sound1"）
                String name = field.getName();
                int resId = field.getInt(null);
                // 手动补后缀
                mp3Files.put(name + ".mp3", resId);
            } catch (Exception e) {
                LogUtil.e(TAG, "Error getting raw file: " + e.getMessage());
            }
        }
        return mp3Files;
    }

    /**
     * 通过资源ID播放 raw 文件夹中的 MP3 文件
     * @param resId MP3 文件资源ID
     */
    public void playRawMp3(int resId) {
        if (mediaPlayer2 == null) {
            mediaPlayer2 = new MediaPlayer();
            setupMediaPlayer(mediaPlayer2, 2);
        }

        try {
            if (mediaPlayer2.isPlaying()) {
                mediaPlayer2.stop();
            }
            mediaPlayer2.reset();

            // 从 raw 资源创建文件描述符
            AssetFileDescriptor afd = getResources().openRawResourceFd(resId);
            if (afd == null) {
                LogUtil.e(TAG, "Failed to open raw resource");
                return;
            }

            mediaPlayer2.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            afd.close();

            mediaPlayer2.prepareAsync();
            mediaPlayer2.setOnPreparedListener(mp -> {
                isPrepared2 = true;
                mp.start();
                updateVolumes();
            });

            isPrepared2 = false;
        } catch (IOException e) {
            LogUtil.e(TAG, "Error playing raw MP3: " + e.getMessage());
        }
    }

    /**
     * 获取 assets 文件夹中的 MP3 文件列表
     * @return MP3 文件名列表
     */
    public List<String> getAssetsMp3Files() {
        List<String> mp3Files = new ArrayList<>();
        try {
            // 获取 assets 文件夹下的所有文件
            String[] files = getAssets().list("");
            if (files != null) {
                for (String file : files) {
                    if (file.toLowerCase().endsWith(".mp3")) {
                        mp3Files.add(file);
                    }
                }
            }
        } catch (IOException e) {
            LogUtil.e(TAG, "Error listing assets files: " + e.getMessage());
        }
        return mp3Files;
    }

    /**
     * 播放 assets 文件夹中的 MP3 文件
     * @param fileName MP3 文件名
     */
    public void playAssetsMp3(String fileName) {
        if (mediaPlayer2 == null) {
            mediaPlayer2 = new MediaPlayer();
            setupMediaPlayer(mediaPlayer2, 2);
        }

        this.url2 = fileName;

        try {
            if (mediaPlayer2.isPlaying()) {
                mediaPlayer2.stop();
            }
            mediaPlayer2.reset();

            // 从 assets 创建文件描述符
            AssetFileDescriptor afd = getAssets().openFd(url2);
            mediaPlayer2.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            afd.close();

            mediaPlayer2.prepareAsync();
            mediaPlayer2.setOnPreparedListener(mp -> {
                isPrepared2 = true;
                mp.start();
                updateVolumes();
            });

            mediaPlayer2.setOnCompletionListener(mp -> {
                isPrepared2 = true;
                mp.start();
            });

            LogUtil.e(TAG, "开始播放 mp3  ==   " + fileName);

            isPrepared2 = false;
        } catch (IOException e) {
            LogUtil.e(TAG, "Error playing assets MP3: " + e.getMessage());
            //Toaster.show("无法播放音频文件");
        }
    }
}